﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using ModelLayer;
using DAL;
using System.Diagnostics;

namespace BusinessLayer
{
    public class Security : IFSecurity
    {
        public Security()
        {
            
        }

        public byte[] CreateSalt(int size)
        {
            //Generate a cryptographic random number.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff = new byte[size];
            rng.GetBytes(buff);

            // Return a Base64 string representation of the random number.
            return buff;
        }


        public byte[] GenerateSaltedHash(byte[] plainText, byte[] salt)
        {
            HashAlgorithm algorithm = new SHA256Managed();

            byte[] plainTextWithSaltBytes =
              new byte[plainText.Length + salt.Length];

            for (int i = 0; i < plainText.Length; i++)
            {
                plainTextWithSaltBytes[i] = plainText[i];
            }
            for (int i = 0; i < salt.Length; i++)
            {
                plainTextWithSaltBytes[plainText.Length + i] = salt[i];
            }

            return algorithm.ComputeHash(plainTextWithSaltBytes);  
        }

        public bool CompareByteArrays(byte[] array1, byte[] array2)
        {
            if (array1.Length != array2.Length)
            {
                return false;
            }

            for (int i = 0; i < array1.Length; i++)
            {
                if (array1[i] != array2[i])
                {
                    return false;
                }
            }

            return true;
        }

        public string GenerateTokenHash()
        {
            return Convert.ToBase64String(Guid.NewGuid().ToByteArray());
        }


        public bool Authenticate(string username, string token)
        {
            ModelLayer.User u = new ModelLayer.User();
            IFUserB user = new UserB();
            u = user.SearchUName(username);
            IFTokenB tokenB = new TokenB();
            ModelLayer.Token t = tokenB.FindToken(u.UserId);
            TimeSpan now = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0);
            Debug.WriteLine("t.expir sddje: " +t.Expire);
            Debug.WriteLine("now: " + now.TotalSeconds);
            if (t.Expire >= (int) now.TotalSeconds)
            {
                Debug.WriteLine("tokenstring: " + token);
                Debug.WriteLine("db tokenid: " + t.TokenId);
                return t.TokenId.Equals(token);
                
            }
            Debug.WriteLine("fejler");
            return false;
        }
    }
}
